<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/5/11
 * Time: 11:17
 */

namespace Admin\Common;


use Gaoming13\WechatPhpSdk\Api;
use Think\Log;

class MyBll
{
    public function Get_accessToken()
    {
        $we=M('sys')->where(array('sys_id'=>1))->find();//读取微信配置参数
        $access_token=json_decode($we['wesys_access_token']);
             
            if(isset($access_token))
            {
                if($access_token->expires_in>time())
                {
                    return $access_token->access_token;
                }else
                {
                    //重新获取accessToken
                    $new_access_token= $this->Create_AccessToken();
                    Log::write("【最新获取的token:".json_encode($new_access_token)."】");
                    if($new_access_token!=false)
                    {
                        return $new_access_token->access_token;
                    }
                }
            }
            else
            {
                //重新获取accessToken
                $new_access_token= $this->Create_AccessToken();
                $token=json_decode($new_access_token);
                if($new_access_token!=false)
                {
                    Log::write("最后返回：".json_encode($new_access_token->access_token));
                    return $new_access_token->access_token;
                }
            }
    
    }

    /**
     * 返回access_token，并向数据库更新access_token
     */
    public function Create_AccessToken()
    {
        $we=M('sys')->where(array('sys_id'=>1))->find();//读取微信配置参数
        //$we["wesys_appid"]   $we["wesys_appsecret"]
        $config['appId']=$we["wesys_appid"];
        $config['appSecret']=$we["wesys_appsecret"];
        $weCath= new Api($config);
        $rel= $weCath->new_access_token();
        if($rel!=false)
        {
            $data["wesys_access_token"]=json_encode($rel);
            $exDb=M("sys")->where(array('sys_id'=>1))->save($data);
            if($exDb>0)
            {
                return $rel;
            }else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
        
    }

    /**
     * 微信api不支持中文转义的json结构
     * @param array $arr
     */
    public static function json_encode($arr) {
        $parts = array ();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys ( $arr );
        $max_length = count ( $arr ) - 1;
        if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ( $arr as $key => $value ) {
            if (is_array ( $value )) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = self::json_encode ( $value ); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
            } else {
                $str = '';
                if (! $is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (is_numeric ( $value ) && $value<2000000000)
                    $str .= $value; //Numbers
                elseif ($value === false)
                    $str .= 'false'; //The booleans
                elseif ($value === true)
                    $str .= 'true';
                else
                    $str .= '"' . addslashes ( $value ) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts [] = $str;
            }
        }
        $json = implode ( ',', $parts );
        if ($is_list)
            return '[' . $json . ']'; //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }
}